// pages/member/coupon_v2/coupon_v2.js
import Dialog from '../../../dist/dialog/dialog';
const skinBehavior = require("../../../utils/themeSkin/skinBehavior");
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  behaviors: [skinBehavior],
  data: {
    imgPath: app.globalData.imgPath,
    language: '',
    selected: 1,
    selectedidx: '1',
    page: 1,
    pageSize: 10,
    total_page: 0,
    isPresenter: false,
    //待使用
    wait_used: [],
    overdue: [],
    used: [],
    usermessage: {
      value: '',
      item: '',
      index: ''
    },
    bottomIndex: '',
    // types:['全部','平台','企业','酒店','指定商品','分类商品','兑换卷','满减卷','折扣卷','快过期'],
    types: [],
    typesIndex: 0,
    kFootshow: true,
    share_coupon: false,
    combine_show: false,
    couponListData: [],
    centerShow:false,
    deleteShow:true,

    //新增样式功能
    couponTabs: [
      {
        title:'待使用',
        value:1,
      },
      {
        title:'已过期',
        value:2,
      },
      {
        title:'已使用',
        value:3,
      }
    ],
    higherIndex:'',
    coThemeColor:'',
    tabIndex:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  closeMoreList(e){
    let {item, index} = e.currentTarget.dataset;
    this.data.couponListData[index].can_spreadShow = false;
    this.setData({
      couponListData:this.data.couponListData
    })
  },
  tapMoreList(e){
    let {index,item} = e.currentTarget.dataset;
    this.setData({
      higherIndex:index
    })
    if(!item.can_spreadShow){
      if(item.can_spreadShow_list && item.can_spreadShow_list.length > 0){
        this.data.couponListData[index].can_spreadShow = true;
        this.setData({
          couponListData:this.data.couponListData,
        })
        return
      }
      this.getCouponList(item.coupon_id, index)
    }
  },
  getCouponList(cid, ind){
    let urlStr = app.getNetAddresss("coupon.member-coupon.get-time-spread-coupon");
    app._postNetWork({
      url: urlStr,
      data:{
        coupon_id: cid, coupon_type: this.data.typesIndex
      },
      success: (resdata)=> {
        var res = resdata.data;
        if (res.result == 1) {
          this.data.couponListData[ind].can_spreadShow_list = res.data;
          this.data.couponListData[ind].can_spreadShow = true;
          this.setData({
            couponListData:this.data.couponListData
          })
        }else{
          app.tips(res.msg)
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  goDetail(event) {
    let {item} = event.detail || {};
    if(!item.is_effective) {
      //待生效不跳转详情
      app.tips(`生效时间：${item.effective_time_str}`);
      return
    }
    if(item.can_spread || this.data.selected == 2 || this.data.selected == 3){
      // 折叠显示展开收起点击不跳转详情
      return
    }
    wx.navigateTo({
      url: `/packageA/member/coupon_v2_detail/coupon_v2_detail?id=${item.id}&combine=${item.combine}&combine_show=${this.data.combine_show}`,
    });
  },
  setTypesIndex(evt) {
    let {index,item} = evt.currentTarget.dataset;
    if (index == this.data.tabIndex) return;
    this.setData({
      typesIndex: item.id,
      tabIndex:index,
    });
    this._getNetData(this.data.selected, this.data.typesIndex);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync('langIndex');
    this.setData({
      'language': language.en
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this._initData();
    this._getNetData(1, this.data.typesIndex);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.isLoadMore) {
      this._getMoreData(this.data.selectedidx, this.data.typesIndex);
    } else {
      console.log('没有更多数据');
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  onShareTimeline(){},
  colorFin(a){
    a=a.substring(1);  
    a=a.toLowerCase();  
    let b=new Array();  
    for(let x=0;x<3;x++){  
      b[0]=a.substr(x*2,2);  
      b[3]="0123456789abcdef";  
      b[1]=b[0].substr(0,1);  
      b[2]=b[0].substr(1,1);  
      b[20+x]=b[3].indexOf(b[1])*16+b[3].indexOf(b[2]);  
    }  
    return b[20]+","+b[21]+","+b[22];
  },
  //发起http请求
  _getNetData(type, coupon_type) {
    if (wx.tempCqSwipeCell) {
      wx.tempCqSwipeCell.setData({
        prevBox: 0
      });
    }
    this.setData({
      couponListData: [],
    });
    let that = this;
    this.data.page = 1;
    let urlStr = app.getNetAddresss("coupon.member-coupon.coupons-of-member-by-status-v2");

    if (app.globalData.store_alone_temp == 1) {
      // 开启企业独立模块
      urlStr = app.getNetAddresss("plugin.store-alone-temp.frontend.coupon.coupons-of-member-by-status-v2");
    }

    urlStr += "&status_request=" + type;
    urlStr += "&coupon_type=" + coupon_type;
    urlStr += "&page=1";
    app._getNetWork({
      url: urlStr,
      data:{basic_info:1},
      success: (resdata)=> {
        var res = resdata.data;
        if (res.result == 1) {
          let themeColor = res.basic_info?.theme_color;
          var myData = res.data;
          that.page = 1;
          that.data.total_page = res.data.data.last_page ? res.data.data.last_page : 1;
          let couponList = myData.data.data || [];
          that.data.isLoadMore = true;
          if (res.data.set) {
            that.setData({
              isPresenter: res.data.set.transfer,
              centerShow:res.data.set.center_show,
              deleteShow:res.data.set.delete_show,
            });
          }
          if (res.data.search_array) {
            that.setData({
              types: res.data.search_array || []
            });
            couponList.map((item,index) => {
              item.openIs = false;
              item.ind = index;
            });
          }

          that.setData({
            couponListData: couponList,
            coThemeColor:that.colorFin(themeColor) || that.colorFin('#F15353'),
            combine_show:res.data.combine_show
          });
          if(!app._isTextEmpty(myData.share_coupon)){
            this.setData({
              share_coupon:myData.share_coupon
            })
          }

        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1000
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  _getMoreData(type, coupon_type) {
    this.data.isLoadMore = false; // 防止多次请求分页数据
    if (this.data.page >= this.data.total_page) {
      // that.loading = true;
      return;
    } else {
      this.data.page += 1;
      let urlStr = app.getNetAddresss("coupon.member-coupon.coupons-of-member-by-status-v2");
      if (app.globalData.store_alone_temp == 1) {
        // 开启企业独立模块
        urlStr = app.getNetAddresss("plugin.store-alone-temp.frontend.coupon.coupons-of-member-by-status-v2");
      }

      urlStr += "&status_request=" + type;
      urlStr += "&coupon_type=" + coupon_type;
      urlStr += "&page=" + this.data.page;
      app._getNetWork({
        url: urlStr,
        success: (resdata)=> {
          var res = resdata.data;
          if (res.result == 1) {
            var myData = res.data;
            let couponList = myData.data.data || [];
            couponList.map((item,index) => {
              item.openIs = false;
              item.ind = index;
            });
            this.data.isLoadMore = true;
            this.setData({
              couponListData: this.data.couponListData.concat(couponList),
            });
          } else {
            this.data.isLoadMore = false;
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1000
            });
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }
  },
  //切换优惠券状态列表
  switchItem(event) {
    let {name} = event.detail;
    this.setData({
      selected:name
    })
    this._getNetData(name, this.data.typesIndex);
  },
  _initData() {
    this.setData({
      page: 1,
      goload: true,
      total_page: 0,
      allLoaded: false,
      isLoadMore: true,
      isPresenter: false
    });

  },
  //子组件事件
  delItem(event) {
    let {item,index} = event.detail || {};
    Dialog.confirm({
      title:'提示',
      message: `是否删除优惠券${item.belongs_to_coupon?.name}`,
    })
      .then(() => {
        // on confirm
        if(this.data.selected !== 1) {
          this.data.couponListData[index].num = 1;
        }
        this.delteteItem(item,index,this.data.higherIndex);
      })
      .catch(() => {
        // on cancel
      });
  },
  delteteItem(item,index,higherIndex) {
    let urlStr = app.getNetAddresss("coupon.member-coupon.delete");
    urlStr += `&id=${item.id}`;
    if (wx.tempCqSwipeCell) {
      wx.tempCqSwipeCell.setData({
        prevBox: 0
      });
    }
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          //没有多张的情况删除优惠券
          if(!item.can_spreadShow_list && this.data.couponListData[higherIndex]?.can_spreadShow) {
            if(this.data.couponListData[higherIndex].can_spreadShow_list[index].num == 1) {
              this.data.couponListData[higherIndex].can_spreadShow_list.splice(index,1);
            } else {
              //总优惠券折叠状态，删除数量
              this.data.couponListData[higherIndex].can_spreadShow_list[index].num--;
              this.setData({
                [`couponListData[${higherIndex}].can_spreadShow_list[${index}].num`]:this.data.couponListData[higherIndex].can_spreadShow_list[index].num
              })
            }
            let couponArr = this.data.couponListData[higherIndex].can_spreadShow_list;
            let num = 0;
            if(couponArr && couponArr.length > 0) {
              couponArr.forEach(element => {
                num += element.num
              });
            }
            this.data.couponListData[higherIndex].can_spreadShow = false;
            this.data.couponListData[higherIndex].num = num;
            this.setData({
              couponListData:this.data.couponListData
            })
          } else {
            console.log('删除单个优惠券');
            //删除单个优惠券
            let couponNum = this.data.couponListData[index].num;
            if(this.data.couponListData[index].num == 1) {
              this.data.couponListData.splice(index,1)
              this.setData({
                couponListData:this.data.couponListData
              })
            } else {
              couponNum--;
              let childArr = [];
              //判断没有折叠状态优惠券出现多张一样的
              if(this.data.couponListData[index].can_spreadShow_list) {
                childArr = this.data.couponListData[index].can_spreadShow_list.splice(-1,1);
              }
              this.setData({
                [`couponListData[${index}].num`]:couponNum,
                [`couponListData[${index}].can_spreadShow_list`]:childArr
              })
            }
          }
          
          wx.showToast({
            icon: 'none',
            title: '操作成功',
            duration: 1000
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1000
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  gocouponStore() {
    //跳转到领卷中心
    wx.redirectTo({
      url: '/packageD/coupon/coupon_store'
    });
  },
  tabrshowbtn(e) {
    let bol = e.detail;
    if (bol) {
      this.setData({
        kFootshow: false
      });
    }
  }
});